import { useRef } from "react";
import { useEffect } from "react";
import { useState } from "react";

const useUsers = () => {
  const [users, setUsers] = useState([]);
  const timerRef = useRef();

  useEffect(() => {
    const onFetch = () => {
      fetch("https://v2.huiyidun.com/api/vco30/3dlogo")
        .then((res) => res.json())
        .then((res) => {
          if (!res.data || res.data.length === 0) {
            timerRef.current = setTimeout(() => {
              onFetch();
            }, 1000);
            return;
          }

          setUsers(
            res.data.map((item) => ({
              id: item.id,
              avatar: item.photo,
            }))
          );
        });
    };

    onFetch();
    return () => {
      clearTimeout(timerRef.current);
    };
  });

  return users;
};

export default useUsers;
